using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using FluorineFx;
using Jon.Adventureworks.Core.Data;
using Jon.Adventureworks.Core.ExtensionMethods;
using Jon.Adventureworks.Core.Objects;

namespace Jon.Adventureworks.Fluorine
{
    /// <summary>
    /// Fluorine sample service.
    /// </summary>
    [RemotingService("fluorine Contact Service")]
    public class ContactService
    {
        public ContactService()
        {
        }

        public string Echo(string text)
        {
            return "Gateway echo: " + text;
        }

        public List<ContactDTO> GetContacts(int startRowIndex, int maximumRows, string searchFilter)
        {
            try
            {
                AdventureWorksContextDataContext advData = new AdventureWorksContextDataContext(ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString);
                List<ContactDTO> contactList = new List<ContactDTO>();
                IEnumerable<Contact> query;

                if (searchFilter.IsNullOrEmpty())
                {
                    query = advData.Contacts.Skip(startRowIndex).Take(maximumRows).Where(p => p.LastName.StartsWith(searchFilter));
                }
                else
                {
                    query = advData.Contacts.Skip(startRowIndex).Take(maximumRows);
                }

                ParseQuery(ref contactList, query);
                return contactList;
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        }

        private static void ParseQuery(ref List<ContactDTO> contactList, IEnumerable<Contact> query)
        {
            foreach (Contact con in query)
            {
                contactList.Add(new ContactDTO
                {
                    ContactId = con.ContactID,
                    NameStyle = con.NameStyle,
                    Title = con.Title,
                    FirstName = con.FirstName,
                    LastName = con.LastName,
                    MiddleName = con.MiddleName,
                    Suffix = con.Suffix,
                    EmailAddress = con.EmailAddress,
                    EmailPromotion = con.EmailPromotion,
                    Phone = con.Phone,
                    AdditionalContactInfo = con.AdditionalContactInfo,
                    ModifiedDate = con.ModifiedDate
                });
            }
        }
    }
}
